<template>
  <view>
    <u-navbar
      :customBack="backToList"
      v-if="!$isWeixin()"
      :title="Type == 1 ? '关停' : '并转'"
      :titleBold="true"
    ></u-navbar>

    <u-tabs :list="tabList" active-color="#FF7A23" :current="tabIndex" @change="onTabChange"></u-tabs>

    <view v-if="tabIndex === 0" class="">
      <u-cell-group :border="false">
        <u-cell-item
          :border-bottom="Level == 3"
          v-if="Level == 2 || Level == 3"
          title="一级经销商名称"
          :arrow="false"
          :value="First_Dealer_BaseInfo.Name"
        ></u-cell-item>
        <u-cell-item
          :border-bottom="false"
          v-if="Level == 3"
          title="二级经销商名称"
          :arrow="false"
          :value="Double_Dealer_BaseInfo.Name"
        ></u-cell-item>

        <basic-information
          v-if="Level == 1 || Level == 2"
          :showParent="false"
          :showDeliveryAddress="false"
          :showGrade="false"
          :showReview="false"
          :level="Level"
          :metadata="DataBaseInfo"
          :data="ThisDealerInfo"
          :loadCity="loadCity"
        ></basic-information>

        <store-information :loadCity="loadCity" :data="Door_Dealer_BaseInfo" v-if="Level == 3"></store-information>

        <view class="u-p-30"><u-button @click="$u.route({ type: 'back' })">返回列表</u-button></view>
      </u-cell-group>
    </view>

    <view v-if="tabIndex === 1" class="">
      <u-cell-group>
        <u-cell-item title="申请类型" :arrow="false">
          <text v-if="Type == 1">关停</text>
          <text v-if="Type == 2">并转</text>
        </u-cell-item>

        <u-cell-item v-if="Type == 1" title="申请原因" :arrow="false">
          <u-radio-group v-model="form.ApplyForReasonId">
            <view class="grid-2">
              <u-radio v-for="(item, index) in DataBaseInfo.DealerShutDown_BaseList" :key="index" :name="item.Key">
                {{ item.Value }}
              </u-radio>
            </view>
          </u-radio-group>
        </u-cell-item>

        <u-cell-item v-if="Type == 2" title="申请原因" :arrow="false">
          <u-radio-group v-model="form.ApplyForReasonId" @change="onShiftReasonChange">
            <view class="grid-2">
              <u-radio v-for="(item, index) in DataBaseInfo.DealerAndGoReason_BaseList" :key="index" :name="item.Key">
                {{ item.Value }}
              </u-radio>
            </view>
          </u-radio-group>
        </u-cell-item>

        <u-cell-item
          :arrow="false"
          title="迁移父级"
          v-if="form.ApplyForReasonId == 20 || form.ApplyForReasonId == 17 || form.ApplyForReasonId == 19"
        >
          <u-input
            :value="currentLevel1 && currentLevel1.label"
            @click="showLevel1 = true"
            inputAlign="right"
            type="select"
            :selectOpen="showLevel1"
            placeholder="请选择父级"
          ></u-input>
        </u-cell-item>

        <u-cell-item :arrow="false" title="迁移子集" v-if="form.ApplyForReasonId == 20">
          <u-input
            :value="currentLevel2 && currentLevel2.label"
            @click="showLevel2 = true"
            inputAlign="right"
            type="select"
            :selectOpen="showLevel2"
            placeholder="请选择子级"
          ></u-input>
        </u-cell-item>

        <u-cell-item title="审核流品牌" :arrow="false" :border-bottom="false" required>
          <u-radio-group v-model="form.Aub_Brand">
            <view class="grid-2">
              <u-radio :label-size="26" :name="5">八喜</u-radio>
              <u-radio :label-size="26" :name="6">夏贝</u-radio>
              <u-radio :label-size="26" :name="7">德地氏</u-radio>
              <u-radio :label-size="26" :name="8">伯爵</u-radio>
              <u-radio :label-size="26" :name="0">无</u-radio>
            </view>
          </u-radio-group>
        </u-cell-item>
        <u-cell-item :arrow="false" style="padding: 0 30rpx;">
          <view style="color: red; text-align: left;">
            请选择审核流品牌，此选项是根据所选品牌指定对应审核流，选择“无”代表无需根据品牌判断使用指定审核流，在所选品牌查找不到审核流信息时，会查询所有审核流中的第一条做为审核流程
          </view>
        </u-cell-item>

        <u-cell-item title="其他备注" :arrow="false" v-if="form.ApplyForReasonId == 10">
          <u-input type="textarea" placeholder="其他备注" inputAlign="right" v-model="form.OtherNote"></u-input>
        </u-cell-item>

        <u-cell-item :arrow="false" title="申请时间">
          <u-input
            :value="$u.date(form.Date * 1000, 'yyyy-mm-dd')"
            inputAlign="right"
            placeholder="请选择"
            disabled
            @click="showTimePick = true"
            type="select"
            :selectOpen="showTimePick"
          ></u-input>
          <u-picker
            :default-time="$u.date(form.Date * 1000, 'yyyy-mm-dd')"
            @confirm="onTimePickerChange"
            v-model="showTimePick"
            mode="time"
            :params="{ year: true, month: true, day: true, hour: false, minute: false, second: false }"
          ></u-picker>
        </u-cell-item>

        <u-cell-item title="申请备注" :arrow="false">
          <u-input type="textarea" inputAlign="right" v-model="form.Remark" placeholder="申请备注"></u-input>
        </u-cell-item>
      </u-cell-group>

      <view class="u-p-30 u-flex">
        <u-button @click="$u.route({ type: 'back' })">返回列表</u-button>
        <u-button type="warning" @click="onSubmit">提交申请</u-button>
      </view>

      <u-select
        :default-value="[level1Index]"
        @confirm="onLevelChange($event, 1)"
        v-model="showLevel1"
        :list="level1List"
        value-name="Key"
        label-name="Value"
      ></u-select>

      <u-select
        :default-value="[level2Index]"
        @confirm="onLevelChange($event, 2)"
        v-model="showLevel2"
        :list="level2List"
        value-name="Key"
        label-name="Value"
      ></u-select>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabList: [{ name: '基本信息' }, { name: '渠道信息调整' }],
      tabIndex: 0,

      Level: null,
      Type: 1,
      loadCity: false,

      DataBaseInfo: {
        BusinessCategory_BaseList: [],
        CompetingGoodsBrandA_BaseList: [],
        CompetingGoodsBrandB_BaseList: [],
        CompetingGoodsBrandC_BaseList: [],
        DealerApplyFor_BaseList: [],
        DealerGrade_BaseList: [],
        DealerMaterialRequirements_BaseList: [],
        DealerShutDown_BaseList: [],
        DealerType_BaseList: [],
        DealerAndGoReason_BaseList: []
      },

      First_Dealer_BaseInfo: {},
      Double_Dealer_BaseInfo: {},
      Door_Dealer_BaseInfo: {},
      This_Dealer_OtherInfo: {},
      This_Dealer_RelationList: [],

      ThisDealerInfo: {
        Dealer_BaseInfo: {
          Account: '',
          Address: '',
          CityId: 610100,
          Created: 1460613600,
          DealerId: 114,
          Delivery_Address: '',
          Delivery_CityId: 610100,
          Delivery_DistrictId: 659020,
          Delivery_ProvinceId: 610000,
          DistrictId: 659020,
          IsFictitious: 0,
          KeDealerNo: '01000090',
          Level: 1,
          LevelName: '',
          Mobile: '',
          Name: '',
          NickName: '',
          Parent_DealerId: 90,
          Parent_Name: '',
          ProvinceId: 610000,
          Referred: '',
          State: 4,
          Telephone: ''
        },
        Dealer_OtherInfo: {
          BlessingNote: '',
          BossBirthday: 1626192000,
          BossName: '',
          BossPhone: '',
          BusinessCategory: '',
          BusinessLicenseA: '',
          CompetingGoodsBrandA: '',
          CompetingGoodsBrandB: '',
          CompetingGoodsBrandC: '',
          DealerGrade: 1,
          DealerType: 1,
          IsSign: 2,
          IsVIP: 1,
          LastYearsBDRSales: 14001,
          PeopleNum: 25,
          PercentageBDRSales: 35,
          TotalSales: 40001,
          TreatyPhoto: 'o_1ed682sou1iuf2lmc37rc31jjjd.png',
          TreatyPhotoType: 1
        },
        Dealer_RelationList: []
      },

      showTimePick: false,

      /**
       * 并转原因 (并转功能页面才有) 注意 这里互动效果为：
       * ①降成二级+变更所属一级 出现迁移父级一个搜索下拉   √
       * ②升成一级 不出现下拉框												√
       * ③变更所属二级 出现迁移父级 + 子级 2个搜索下拉框	√
       * ④ 父级下拉框 代表Level=1 子集代表Level=2 在下拉搜索接口：PostDealerDic 的时候会用到
       */
      showLevel1: false,
      level1List: [],
      level1Index: -1,
      currentLevel1: null,
      showLevel2: false,
      level2List: [],
      level2Index: -1,
      currentLevel2: null,

      form: {
        // 点击列表进入的经销商ID
        DealerId: null,
        // 申请类型 1.新增
        ApplyForType: 1,
        // 申请原因 主原因
        ApplyForReasonId: null,
        // 申请原因 次原因 （选了物料需求或者费用需求之后互动的 复选） 比如 12,13,14
        Requirements: '',
        // 其他备注 勾选申请/关停/并转原因中的其他选项 会出现其他备注 这里就是其他备注 （这个和申请备注不是一个字段噢 别搞错了）
        OtherNote: '',
        // 并转父级经销商ID 并转才传
        ParentId: null,
        // 并转子集经销商 并转才传
        AndGoSecondId: null,
        // 申请/关停/并转时间
        Date: parseInt(new Date().getTime() / 1000),
        // 申请/关停/并转备注
        Remark: '',
        Aub_Brand: ''
      }
    };
  },

  onLoad(options) {
    if (options.DealerId) {
      this.form.DealerId = options.DealerId;
    }
    if (options.Level) {
      this.Level = options.Level;
    }
    if (options.Type) {
      this.Type = options.Type;

      if (this.$isWeixin()) {
        uni.setNavigationBarTitle({
          title: this.Type == 1 ? '关停' : '并转'
        });
      }

      if (this.Type == 1) {
        this.form.ApplyForType = 2;
      }
      if (this.Type == 2) {
        this.form.ApplyForType = 3;
      }
    }

    this.init();
  },

  methods: {
    backToList() {
      uni.navigateTo({
        url: '/pages/home/home'
      });
    },

    onTabChange(index) {
      this.tabIndex = index;
    },
    onTimePickerChange(e) {
      this.form.Date = new Date(`${e.year}-${e.month}-${e.day}`).getTime() / 1000;
    },
    onRequirementsChange(e) {
      this.form.Requirements = e.toString();
    },

    onShiftReasonChange(e) {
      this.resetLevel(1);
      this.resetLevel(2);
      if (e == 17 || e == 20 || e == 19) {
        this.getLevelList(1);
      } else {
      }
    },

    onLevelChange(e, level) {
      // 此处逻辑是为了解决打开下拉框后不做选择直接确定后不会选择第一项的问题
      let selected;
      if (!e[0].value || !e[0].label) {
        if (level == 1) {
          if (this.level1List.length > 0) {
            selected = {
              label: this.level1List[0].Value,
              value: this.level1List[0].Key
            };
          }
        }
        if (level == 2) {
          if (this.level2List.length > 0) {
            selected = {
              label: this.level2List[0].Value,
              value: this.level2List[0].Key
            };
          }
        }
      } else {
        selected = e[0];
      }

      if (level == 1) {
        this.currentLevel1 = selected;
        this.level1Index = this.level1List.findIndex(item => item.Key == e[0].value);
        this.form.ParentId = selected.value;

        this.getLevelList(2, selected.value);
        this.resetLevel(2);
      }
      if (level == 2) {
        this.currentLevel2 = selected;
        this.level2Index = this.level2List.findIndex(item => item.Key == e[0].value);
        this.form.AndGoSecondId = selected.value;
      }
    },

    // 重置下拉框相关属性
    // 比如: 选择了父级后重置子集列表及之前选中的子集选项.
    resetLevel(level) {
      if (level == 1) {
        this.currentLevel1 = null;
        this.level1Index = -1;
        this.level1List = [];
        this.form.ParentId = null;
      }

      if (level == 2) {
        this.currentLevel2 = null;
        this.level2Index = -1;
        this.level2List = [];
        this.form.AndGoSecondId = null;
      }
    },

    // 获取各等级下拉选项
    getLevelList(level, parentId) {
      this.$u.api
        .getDealerDic({
          Level: level,
          ParentId: parentId
        })
        .then(res => {
          const { ResultCode, ResultMessage, DealerList } = res;
          if (level == 1) {
            this.level1List = DealerList;
          }
          if (level == 2) {
            this.level2List = DealerList;
          }
        });
    },

    onSubmit() {
      console.log(this.form);

      // 关停
      let fn;
      if (this.Type == 1) {
        fn = this.$u.api.closeDealer;
      }
      if (this.Type == 2) {
        fn = this.$u.api.shiftDealer;
      }

      if (fn) {
        fn(this.form).then(res => {
          const { ResultCode, ResultMessage } = res;
          if (ResultCode == 1) {
            this.$u.toast(ResultMessage);
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        });
      }
    },
    init() {
      this.$u.api
        .closeDealerInit({
          DealerId: this.form.DealerId,
          Level: this.Level
        })
        .then(res => {
          const {
            ResultCode,
            ResultMessage,
            DataBaseInfo,
            First_Dealer_BaseInfo,
            Double_Dealer_BaseInfo,
            Door_Dealer_BaseInfo,
            This_Dealer_OtherInfo,
            This_Dealer_RelationList
          } = res;

          if (ResultCode === 1) {
            this.DataBaseInfo = DataBaseInfo;

            if (this.Level == 1) {
              this.ThisDealerInfo.Dealer_BaseInfo = First_Dealer_BaseInfo;
            }
            if (this.Level == 2) {
              this.ThisDealerInfo.Dealer_BaseInfo = Double_Dealer_BaseInfo;
            }
            if (this.Level == 3) {
              this.ThisDealerInfo.Dealer_BaseInfo = Door_Dealer_BaseInfo;
            }
            this.ThisDealerInfo.Dealer_OtherInfo = This_Dealer_OtherInfo;
            this.ThisDealerInfo.Dealer_RelationList = This_Dealer_RelationList;

            this.First_Dealer_BaseInfo = First_Dealer_BaseInfo;
            this.Double_Dealer_BaseInfo = Double_Dealer_BaseInfo;
            this.Door_Dealer_BaseInfo = Double_Dealer_BaseInfo;

            this.DataBaseInfo.BusinessCategory_BaseList.forEach(item => {
              item.checked = This_Dealer_OtherInfo.BusinessCategory.split(',').indexOf(String(item.Key)) > -1;
            });
            this.DataBaseInfo.CompetingGoodsBrandA_BaseList.forEach(item => {
              item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandA.split(',').indexOf(String(item.Key)) > -1;
            });
            this.DataBaseInfo.CompetingGoodsBrandB_BaseList.forEach(item => {
              item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandB.split(',').indexOf(String(item.Key)) > -1;
            });
            this.DataBaseInfo.CompetingGoodsBrandC_BaseList.forEach(item => {
              item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandC.split(',').indexOf(String(item.Key)) > -1;
            });

            this.loadCity = true;
          }
        });
    }
  }
};
</script>

<style lang="scss"></style>
